import random

from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _

from captchas.widgets import CaptchaWidget

from Captcha import PersistentFactory


class CaptchaField(forms.CharField):
    """
    Captcha form field

    Originally based on the source code found here:
    http://kill9.eu/2007/08/17/captcha-widgets-django/
    """
    widget = CaptchaWidget

    def clean(self, values):
        value, captcha_id = values
        factory = PersistentFactory(settings.CAPTCHA_PERSISTENCE)
        test = factory.get(str(captcha_id))
        factory.storedInstances.close()
        if not test or not test.valid:
            raise forms.ValidationError(_('Please refresh this page to get '
                                          'new image'))
        if not test.testSolutions([value.strip()]):
            raise forms.ValidationError(_('You did not type the correct '
                                          'text'))
        return ''

